
import './login.less'
import * as types from '@/vuex/mutation-types'

export default {
  data() {
    const validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入公司邮箱'));
      } else if (!/^[a-zA-Z0-9]+@dafy\.com$/.test(value)) {
        callback(new Error('邮箱格式错误，格式必须为xxx@dafy.com结尾的邮箱'))
      }
      else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      refFormName: 'loginForm',
      showPassword: false,
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { validator: validateAccount, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  computed: {
    typeType() {
      return this.showPassword ? 'text' : 'password'
    }
  },
  created() {
    this.$store.state.common.breadData = []
  },
  methods: {
    switchPassword() {
      if (!this.showPassword) {
        this.showPassword = true
      } else {
        this.showPassword = false
      }
    },
    query() {
      this.$store.dispatch('userMenus')
      this.$store.dispatch('getUnProcess')
      this.$store.dispatch('queryAllDict')
    },
    submitForm() {
      this.$refs[this.refFormName].validate((valid) => {
        if (valid) {
          this.loading = true
          api.login(this.loginForm)
            .then(res => {
              this.loading = false
              this.$store.commit(types.SET_USER_INFO, res)
              this.query()
              var _redirect = this.$route.query.redirect
              _redirect = _redirect || '/index'
              this.$router.push(_redirect)
            })
            .catch(err => {
              this.loading = false
              console.log(err)
            })
        } else {
          return false
        }
      })
    }
  }
}